const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const { Op, Sequelize } = require('sequelize');
const { User, Order, Product, PointsTransaction } = require('../models');
const auth = require('../middleware/auth');
const adminAuth = require('../middleware/adminAuth');
const userAdminAuth = require('../middleware/userAdminAuth');

// 管理员登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // 查找管理员用户
    const admin = await User.findOne({
      where: {
        [Op.or]: [
          { phone: username },
          { email: username },
          { username: username }
        ],
        role: 'admin'
      }
    });
    
    if (!admin) {
      return res.status(401).json({
        success: false,
        message: '管理员账户不存在'
      });
    }
    
    // 验证密码
    const isValidPassword = await admin.validatePassword(password);
    if (!isValidPassword) {
      return res.status(401).json({
        success: false,
        message: '密码错误'
      });
    }
    
    // 检查账户状态
    if (admin.status !== 1) {
      return res.status(401).json({
        success: false,
        message: '管理员账户已被禁用'
      });
    }
    
    // 生成JWT token
    const token = jwt.sign(
      { 
        id: admin.id, 
        role: admin.role,
        username: admin.username 
      },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );
    
    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        admin: {
          id: admin.id,
          username: admin.username,
          role: admin.role,
          permissions: admin.permissions || []
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '登录失败',
      error: error.message
    });
  }
});

// 获取管理员信息
router.get('/profile', auth, userAdminAuth, async (req, res) => {
  try {
    const admin = await User.findById(req.user.id, {
      attributes: { exclude: ['password'] }
    });
    
    res.json({
      success: true,
      data: admin
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取管理员信息失败',
      error: error.message
    });
  }
});

// 获取系统概览数据
router.get('/dashboard', auth, userAdminAuth, async (req, res) => {
  try {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    
    const [
      totalUsers,
      todayUsers,
      totalOrders,
      todayOrders,
      totalRevenue,
      todayRevenue,
      totalProducts,
      activeProducts
    ] = await Promise.all([
      User.count({ where: { role: 'user' } }),
      User.count({ 
        where: {
          role: 'user',
          created_at: { [Op.gte]: today }
        }
      }),
      Order.count(),
      Order.count({
        where: {
          createdAt: { [Op.gte]: today }
        }
      }),
      Order.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('finalAmount')), 'total']],
        where: { status: 'completed' },
        raw: true
      }),
      Order.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('finalAmount')), 'total']],
        where: { 
          status: 'completed',
          createdAt: { [Op.gte]: today }
        },
        raw: true
      }),
      Product.count(),
      Product.count({ where: { status: 1 } })
    ]);
    
    res.json({
      success: true,
      data: {
        users: {
          total: totalUsers,
          today: todayUsers
        },
        orders: {
          total: totalOrders,
          today: todayOrders
        },
        revenue: {
          total: totalRevenue?.total || 0,
          today: todayRevenue?.total || 0
        },
        products: {
          total: totalProducts,
          active: activeProducts
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取概览数据失败',
      error: error.message
    });
  }
});

// 用户管理 - 获取用户列表
router.get('/users', auth, userAdminAuth, async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 20, 
      search, 
      status, 
      role = 'user',
      startDate,
      endDate 
    } = req.query;
    
    const whereClause = { role };
    
    if (search) {
      whereClause[Op.or] = [
        { nickname: { [Op.like]: `%${search}%` } },
        { phone: { [Op.like]: `%${search}%` } }
      ];
    }
    
    if (status !== undefined) {
      whereClause.status = parseInt(status);
    }
    
    if (startDate || endDate) {
      const dateCondition = {};
      if (startDate) {
        dateCondition[Op.gte] = new Date(startDate);
      }
      if (endDate) {
        dateCondition[Op.lte] = new Date(endDate);
      }
      whereClause.created_at = dateCondition;
    }
    
    const users = await User.findAll({
      where: whereClause,
      attributes: { exclude: ['password'] },
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: (page - 1) * limit
    });
    
    const total = await User.count({ where: whereClause });
    
    res.json({
      success: true,
      data: {
        users,
        pagination: {
          current: parseInt(page),
          total: Math.ceil(total / limit),
          pageSize: parseInt(limit),
          totalItems: total
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户列表失败',
      error: error.message
    });
  }
});

// 用户管理 - 更新用户状态
router.put('/users/:id/status', auth, userAdminAuth, async (req, res) => {
  try {
    const { status } = req.body;
    
    const user = await User.findByIdAndUpdate(
      req.params.id,
      { status: parseInt(status) },
      { new: true }
    ).select('-password');
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    res.json({
      success: true,
      message: '用户状态更新成功',
      data: user
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: '更新用户状态失败',
      error: error.message
    });
  }
});

// 用户管理 - 获取用户详情
router.get('/users/:id', auth, userAdminAuth, async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id, {
      attributes: { exclude: ['password'] }
    });
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 获取用户统计数据
    const [orderCount, totalSpent, pointsEarned, pointsSpent] = await Promise.all([
      Order.count({ where: { userId: user.id } }),
      Order.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('finalAmount')), 'total']],
        where: { userId: user.id, status: 'completed' },
        raw: true
      }),
      PointsTransaction.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('amount')), 'total']],
        where: { userId: user.id, type: 'earn' },
        raw: true
      }),
      PointsTransaction.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.fn('ABS', Sequelize.col('amount'))), 'total']],
        where: { userId: user.id, type: 'spend' },
        raw: true
      })
    ]);
    
    res.json({
      success: true,
      data: {
        user,
        stats: {
          orderCount,
          totalSpent: totalSpent?.total || 0,
          pointsEarned: pointsEarned?.total || 0,
          pointsSpent: pointsSpent?.total || 0
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户详情失败',
      error: error.message
    });
  }
});

// 用户管理 - 更新用户信息
router.put('/users/:id', auth, userAdminAuth, async (req, res) => {
  try {
    const userId = req.params.id;
    const { nickname, phone, memberLevel, role, status } = req.body;
    
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 构建更新数据
    const updateData = {};
    if (nickname !== undefined) updateData.nickname = nickname;
    if (phone !== undefined) updateData.phone = phone;
    if (memberLevel !== undefined) updateData.member_level = memberLevel;
    if (role !== undefined) updateData.role = role;
    if (status !== undefined) updateData.status = status;
    
    await user.update(updateData);
    
    res.json({
      success: true,
      message: '用户信息更新成功',
      data: {
        id: user.id,
        nickname: user.nickname,
        phone: user.phone,
        memberLevel: user.member_level,
        role: user.role,
        status: user.status
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新用户信息失败',
      error: error.message
    });
  }
});

// 商品管理 - 获取商品列表
router.get('/products', auth, userAdminAuth, async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 20, 
      search, 
      category, 
      status,
      sortBy = 'createdAt',
      sortOrder = 'desc'
    } = req.query;
    
    const whereClause = {};
    
    if (search) {
      whereClause[Op.or] = [
        { name: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } }
      ];
    }
    
    if (category) {
      whereClause.category = category;
    }
    
    if (status !== undefined) {
      whereClause.status = parseInt(status);
    }
    
    const orderDirection = sortOrder === 'desc' ? 'DESC' : 'ASC';
    
    const products = await Product.findAll({
      where: whereClause,
      order: [[sortBy, orderDirection]],
      limit: parseInt(limit),
      offset: (page - 1) * limit
    });
    
    const total = await Product.count({ where: whereClause });
    
    res.json({
      success: true,
      data: {
        products,
        pagination: {
          current: parseInt(page),
          total: Math.ceil(total / limit),
          pageSize: parseInt(limit),
          totalItems: total
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取商品列表失败',
      error: error.message
    });
  }
});

// 订单管理 - 获取所有订单
router.get('/orders', auth, userAdminAuth, async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 20, 
      status, 
      userId, 
      startDate, 
      endDate,
      orderNumber
    } = req.query;
    
    const whereClause = {};
    
    if (status) {
      whereClause.status = status;
    }
    
    if (userId) {
      whereClause.userId = userId;
    }
    
    if (orderNumber) {
      whereClause.orderNumber = { [Op.like]: `%${orderNumber}%` };
    }
    
    if (startDate || endDate) {
      const dateCondition = {};
      if (startDate) {
        dateCondition[Op.gte] = new Date(startDate);
      }
      if (endDate) {
        dateCondition[Op.lte] = new Date(endDate);
      }
      whereClause.createdAt = dateCondition;
    }
    
    const orders = await Order.findAll({
      where: whereClause,
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: (page - 1) * limit
    });
    
    const total = await Order.count({ where: whereClause });
    
    res.json({
      success: true,
      data: {
        orders,
        pagination: {
          current: parseInt(page),
          total: Math.ceil(total / limit),
          pageSize: parseInt(limit),
          totalItems: total
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取订单列表失败',
      error: error.message
    });
  }
});

// 订单管理 - 更新订单状态（核销功能）
router.put('/orders/:id/status', auth, userAdminAuth, async (req, res) => {
  try {
    const orderId = req.params.id;
    const { status, adminNotes } = req.body;
    
    // 验证状态值
    const validStatuses = ['pending', 'confirmed', 'processing', 'printing', 'completed', 'cancelled'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的订单状态'
      });
    }
    
    // 查找订单
    const order = await Order.findByPk(orderId, {
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ]
    });
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    // 检查状态转换是否合法
    const currentStatus = order.status;
    const statusFlow = {
      'pending': ['confirmed', 'cancelled'],
      'confirmed': ['processing', 'cancelled'],
      'processing': ['printing', 'cancelled'],
      'printing': ['completed'],
      'completed': [],
      'cancelled': []
    };
    
    if (!statusFlow[currentStatus].includes(status)) {
      return res.status(400).json({
        success: false,
        message: `订单状态不能从 ${currentStatus} 更改为 ${status}`
      });
    }
    
    // 更新订单状态
    const updateData = {
      status,
      updatedAt: new Date()
    };
    
    // 如果有管理员备注，添加到订单中
    if (adminNotes) {
      updateData.adminNotes = adminNotes;
    }
    
    // 如果订单完成，记录完成时间
    if (status === 'completed') {
      updateData.completedAt = new Date();
    }
    
    await order.update(updateData);
    
    // 重新获取更新后的订单数据
    const updatedOrder = await Order.findByPk(orderId, {
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ]
    });
    
    res.json({
      success: true,
      message: '订单状态更新成功',
      data: updatedOrder
    });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新订单状态失败',
      error: error.message
    });
  }
});

// 订单管理 - 获取订单详情
router.get('/orders/:id', auth, userAdminAuth, async (req, res) => {
  try {
    const order = await Order.findByPk(req.params.id, {
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone', 'avatar']
        }
      ]
    });
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    res.json({
      success: true,
      data: order
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取订单详情失败',
      error: error.message
    });
  }
});

// 订单管理 - 获取订单状态统计
router.get('/orders/status-statistics', auth, userAdminAuth, async (req, res) => {
  try {
    const { startDate, endDate, userId } = req.query;
    
    const whereClause = {};
    
    // 验证日期参数
    if (startDate) {
      const start = new Date(startDate);
      if (isNaN(start.getTime())) {
        return res.status(400).json({
          success: false,
          message: '无效的开始日期'
        });
      }
      whereClause.createdAt = whereClause.createdAt || {};
      whereClause.createdAt[Op.gte] = start;
    }
    
    if (endDate) {
      const end = new Date(endDate);
      if (isNaN(end.getTime())) {
        return res.status(400).json({
          success: false,
          message: '无效的结束日期'
        });
      }
      whereClause.createdAt = whereClause.createdAt || {};
      whereClause.createdAt[Op.lte] = end;
    }
    
    // 验证用户ID
    if (userId) {
      const userIdNum = parseInt(userId);
      if (isNaN(userIdNum) || userIdNum <= 0) {
        return res.status(400).json({
          success: false,
          message: '无效的用户ID'
        });
      }
      whereClause.userId = userIdNum;
    }
    
    // 获取各状态订单统计
    const [
      totalOrders,
      pendingOrders,
      confirmedOrders,
      processingOrders,
      printingOrders,
      completedOrders,
      cancelledOrders
    ] = await Promise.all([
      Order.count({ where: whereClause }),
      Order.count({ where: { ...whereClause, status: 'pending' } }),
      Order.count({ where: { ...whereClause, status: 'confirmed' } }),
      Order.count({ where: { ...whereClause, status: 'processing' } }),
      Order.count({ where: { ...whereClause, status: 'printing' } }),
      Order.count({ where: { ...whereClause, status: 'completed' } }),
      Order.count({ where: { ...whereClause, status: 'cancelled' } })
    ]);
    
    res.json({
      success: true,
      data: {
        total: totalOrders,
        pending: { count: pendingOrders },
        confirmed: { count: confirmedOrders },
        processing: { count: processingOrders },
        printing: { count: printingOrders },
        completed: { count: completedOrders },
        cancelled: { count: cancelledOrders }
      }
    });
  } catch (error) {
    console.error('获取订单状态统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取统计数据失败',
      error: error.message
    });
  }
});

// 订单管理 - 获取订单概览统计
router.get('/orders/analytics/overview', auth, userAdminAuth, async (req, res) => {
  try {
    const { days = 30 } = req.query;
    
    const daysAgo = new Date();
    daysAgo.setDate(daysAgo.getDate() - parseInt(days));
    
    const whereClause = {
      createdAt: {
        [Op.gte]: daysAgo
      }
    };
    
    const [
      totalOrders,
      completedOrders,
      cancelledOrders,
      totalRevenue,
      avgOrderValue
    ] = await Promise.all([
      Order.count({ where: whereClause }),
      Order.count({ where: { ...whereClause, status: 'completed' } }),
      Order.count({ where: { ...whereClause, status: 'cancelled' } }),
      Order.sum('finalAmount', { where: { ...whereClause, status: 'completed' } }),
      Order.findOne({
        where: { ...whereClause, status: 'completed' },
        attributes: [[Sequelize.fn('AVG', Sequelize.col('finalAmount')), 'avgValue']]
      })
    ]);
    
    res.json({
      success: true,
      data: {
        totalOrders: totalOrders || 0,
        completedOrders: completedOrders || 0,
        cancelledOrders: cancelledOrders || 0,
        totalRevenue: parseFloat(totalRevenue) || 0,
        avgOrderValue: parseFloat(avgOrderValue?.dataValues?.avgValue) || 0,
        completionRate: totalOrders > 0 ? ((completedOrders / totalOrders) * 100).toFixed(2) : 0
      }
    });
  } catch (error) {
    console.error('获取订单概览统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取概览统计失败',
      error: error.message
    });
  }
});

// 订单管理 - 处理退款
router.post('/orders/:id/refund', auth, userAdminAuth, async (req, res) => {
  try {
    const orderId = parseInt(req.params.id);
    const { refundAmount, refundReason } = req.body;
    
    if (!refundAmount || refundAmount <= 0) {
      return res.status(400).json({
        success: false,
        message: '退款金额必须大于0'
      });
    }
    
    if (!refundReason) {
      return res.status(400).json({
        success: false,
        message: '退款原因不能为空'
      });
    }
    
    const order = await Order.findByPk(orderId);
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    if (order.status !== 'completed') {
      return res.status(400).json({
        success: false,
        message: '只能对已完成的订单进行退款'
      });
    }
    
    // 简单的退款处理 - 更新订单状态和添加备注
    await order.update({
      status: 'refunded',
      adminNotes: `退款处理: ${refundReason}, 退款金额: ${refundAmount}`
    });
    
    res.json({
      success: true,
      message: '退款处理成功'
    });
  } catch (error) {
    console.error('处理退款失败:', error);
    res.status(400).json({
      success: false,
      message: '处理退款失败',
      error: error.message
    });
  }
});

// 订单管理 - 导出订单数据
router.get('/orders/export/excel', auth, userAdminAuth, async (req, res) => {
  try {
    const {
      search,
      status,
      startDate,
      endDate
    } = req.query;
    
    const whereClause = {};
    
    if (status) {
      whereClause.status = status;
    }
    
    if (search) {
      whereClause[Op.or] = [
        { orderNumber: { [Op.like]: `%${search}%` } }
      ];
    }
    
    if (startDate || endDate) {
      const dateCondition = {};
      if (startDate) {
        dateCondition[Op.gte] = new Date(startDate);
      }
      if (endDate) {
        dateCondition[Op.lte] = new Date(endDate);
      }
      whereClause.createdAt = dateCondition;
    }
    
    const orders = await Order.findAll({
      where: whereClause,
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: 1000 // 限制导出数量
    });
    
    const exportData = orders.map(order => ({
      orderNumber: order.orderNumber,
      userId: order.userId,
      userNickname: order.User?.nickname || '',
      userPhone: order.User?.phone || '',
      status: order.status,
      totalAmount: order.totalAmount,
      finalAmount: order.finalAmount,
      pointsUsed: order.pointsUsed,
      createdAt: order.createdAt,
      updatedAt: order.updatedAt
    }));
    
    res.json({
      success: true,
      data: exportData,
      message: `导出 ${exportData.length} 条订单数据`
    });
  } catch (error) {
    console.error('导出订单数据失败:', error);
    res.status(500).json({
      success: false,
      message: '导出订单数据失败',
      error: error.message
    });
  }
});

module.exports = router;